import { defineStore } from 'pinia';
import { type RouteRecordRawNew, type RoteMenuStore, type RouteRecordRaw, nameEnum } from '../types/index.d';


import { routesList } from '@/router/routes';

const Module = import.meta.glob('@/views/**/*.vue');
//懒加载组件
function loadComponent(url: string) {
  const path = Module[`/src/views/${url}`];
  return path;
}
export const useRouteStore = defineStore(nameEnum.ROUTEMENU, {
  /**
   *
   * @returns 全部路由信息 routeList    选中路由  selectedKeys  ，stairMenu 第一层路由
   */
  state: (): RoteMenuStore<RouteRecordRawNew> => {
    return {
      routeList: [],

    };
  },
  getters: {
    getRouteList: (state) => {
      return state.routeList
    }
  },


  actions: {
    /**
     *
     * @param routers 需要动态注册的路由配置
     * @returns   返回动态注册路由
     */
    // 递归添加组件
    dynamicRouter(routers: RouteRecordRawNew[]): RouteRecordRawNew[] {
      const list: RouteRecordRawNew[] = [];
      routers.forEach((itemRouter, index) => {
        // 从本地找组件

        list.push({
          ...itemRouter,
          component: loadComponent(itemRouter.component), //没找到则用默认框架组件
        });
        // 是否存在子集
        if (itemRouter.children && itemRouter.children.length) {
          list[index].children = this.dynamicRouter(itemRouter.children);
        }
      });

      return list;
    },
    // 添加到Route
    setRouteList(list: RouteRecordRawNew[], router: any) {
      //   注册路由
      this.routeList = this.dynamicRouter(list);
      console.log('====>',this.routeList);
      this.routeList.forEach((m) => {
        router.addRoute(m as RouteRecordRaw);
      });
    },
    /**
     * 过滤数据
     * @param val 后端返回的第二层
     * @param routesList 配置的路由
     * @param path /拼接的地址
     * @returns   返回匹配后的数据
     * 
     */
    filterRoute(val: any[], routesList: RouteRecordRawNew[], path?: string): RouteRecordRawNew[] {
      const list: RouteRecordRawNew[] = [];
      routesList.forEach((d) => {
        val?.forEach((m) => {
          // 看有没有子节点相同的
          if (d.children?.length) {
            if (d.meta?.resourceId == m.resourceId) {
              const childrenList = this.filterRoute(m.children ?? [], d.children, path);
              d.children = childrenList ?? [];
            }
          }
          if (d.meta?.resourceId == m.resourceId) {
            list.push({
              ...d,
              // 拼接父节点
              path: `${path}${d.path}`,
            });
          }
        });
      });
      return list;
    },


  },
});
